package com.beiye.drivertransport.SubActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.beiye.drivertransport.R;
import com.beiye.drivertransport.activity.TwoBaseAty;
import com.beiye.drivertransport.bean.CheckBean;
import com.beiye.drivertransport.bean.IllegalLearningPaymentBean;
import com.beiye.drivertransport.bean.LoginUserBean;
import com.beiye.drivertransport.bean.PayMentBean;
import com.beiye.drivertransport.http.Login;
import com.beiye.drivertransport.utils.Constants;
import com.beiye.drivertransport.utils.MessageEvent;
import com.beiye.drivertransport.utils.TiShiDialog;
import com.beiye.drivertransport.utils.UserManger;
import com.beiye.drivertransport.utils.Utils;
import com.beiye.drivertransport.view.LiumRadioGroup;
import com.githang.statusbar.StatusBarCompat;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.UUID;


import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

//违章培训支付界面
public class IllegalLearningPaymentActivity extends TwoBaseAty {

    ImageView img_payback;

    TextView tv_pay3;//购买

    TextView tv_price;//

    TextView tv_balance;//

    TextView tv_money;//

    LiumRadioGroup rg;


    RadioButton radioButton_pay1;

    ImageView img_yu;

    TextView tv_pay2;
    private IWXAPI api;
    private String jumpType;


    @Override
    public int getLayoutId() {
        return R.layout.activity_illegal_learning_payment;

    }

    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.img_payback) {
            finish();
        } else if (id == R.id.tv_pay3) {
            if (Utils.isFastClicker()) {
                return;
            }
            if (tv_pay3.getText().toString().trim().equals("余额购买")) {
                SharedPreferences sp = getSharedPreferences("IllegalLearningPaymentActivity", Context.MODE_PRIVATE);
                String orgId = sp.getString("orgId", "");
                String plateNo = sp.getString("plateNo", "");
                int sn = sp.getInt("sn", 0);
                LoginUserBean userInfo = UserManger.getUserInfo();
                LoginUserBean.DataBean data = userInfo.getData();
                String userId = data.getUserId();
                showLoadingDialog("");
                SharedPreferences dishSp = getSharedPreferences("BusinessSelfinspectionDishinfoActivity", Context.MODE_PRIVATE);
                String discreditId = dishSp.getString("discreditId", "");
                String discreditType = dishSp.getString("discreditType", "");
                String depName = dishSp.getString("depName", "");
                String discreditContent = dishSp.getString("discreditContent", "");

                SharedPreferences eduListSp = getSharedPreferences("BusinessSelfinspectionScoreEducListActivity", Context.MODE_PRIVATE);
                String scoreEducId = eduListSp.getString("scoreEducId", "");

                if (jumpType.equals("homeFgt")) {
                    new Login().getViolationtrainingPayMentApp(userId, orgId, plateNo, sn, IllegalLearningPaymentActivity.this, 1);//车牌号
                } else if (jumpType.equals("dish")) {
                    new Login().vioTrainApplyByDiscreditId(orgId, userId, plateNo, sn + "", depName, discreditType, discreditId, discreditContent, IllegalLearningPaymentActivity.this, 1);
                } else if (jumpType.equals("eduList")) {
                    new Login().vioTrainApplyByScoreEducId(orgId, userId, plateNo, sn + "", scoreEducId, IllegalLearningPaymentActivity.this, 1);
                }
                //new Login().getViolationtrainingPayMentApp(userId,orgId, plateNo,sn,this, 1);
                tv_pay3.setEnabled(false);
            } else if (tv_pay3.getText().toString().trim().equals("充值余额并购买")) {

                boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
                if (!isPaySupported) {
                    TiShiDialog.Builder builder1 = new TiShiDialog.Builder(IllegalLearningPaymentActivity.this);
                    builder1.setMessage("该微信版本不支持微信支付或者未安装微信软件");
                    builder1.setTitle("提示:");
                    builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            ;
                        }
                    });
                    builder1.create().show();
                    return;
                }
                SharedPreferences sp = getSharedPreferences("IllegalLearningPaymentActivity", Context.MODE_PRIVATE);
                float difference = sp.getFloat("difference", 0);
                String orgId = sp.getString("orgId", "");
                LoginUserBean userInfo = UserManger.getUserInfo();
                LoginUserBean.DataBean data = userInfo.getData();
                if (data == null) {
                    return;
                }
                String userId = data.getUserId();
                String phoneSign = getPhoneSign();//设备的唯一标识
                Toast.makeText(IllegalLearningPaymentActivity.this, "获取订单中...", Toast.LENGTH_SHORT).show();
                tv_pay3.setEnabled(false);
                new Login().getbalanceMentApp(userId, orgId, 2, "APP", difference, phoneSign, Constants.APP_ID, this, 2);
            }
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MessageEvent event) {
        if(event.getType()==MessageEvent.TYPE_11)
        {
            SharedPreferences sp = getSharedPreferences("IllegalLearningPaymentActivity", Context.MODE_PRIVATE);
            String orgId = sp.getString("orgId", "");
            String plateNo = sp.getString("plateNo", "");
            int sn = sp.getInt("sn", 0);
            LoginUserBean userInfo = UserManger.getUserInfo();
            LoginUserBean.DataBean data = userInfo.getData();
            String userId = data.getUserId();
            showLoadingDialog("");

            SharedPreferences dishSp=getSharedPreferences("BusinessSelfinspectionDishinfoActivity",Context.MODE_PRIVATE);
            String discreditId=dishSp.getString("discreditId","");
            String discreditType=dishSp.getString("discreditType","");
            String depName=dishSp.getString("depName","");
            String discreditContent=dishSp.getString("discreditContent","");

            SharedPreferences eduListSp=getSharedPreferences("BusinessSelfinspectionScoreEducListActivity",Context.MODE_PRIVATE);
            String scoreEducId=eduListSp.getString("scoreEducId","");

            if(jumpType.equals("homeFgt")){
                new Login().getViolationtrainingPayMentApp(userId, orgId, plateNo, sn, IllegalLearningPaymentActivity.this, 1);//车牌号
            }else if(jumpType.equals("dish")){
                new Login().vioTrainApplyByDiscreditId(orgId,userId,plateNo,sn+"",depName,discreditType,discreditId,discreditContent,IllegalLearningPaymentActivity.this,1);
            }else if(jumpType.equals("eduList")){
                new Login().vioTrainApplyByScoreEducId(orgId,userId,plateNo,sn+"",scoreEducId,IllegalLearningPaymentActivity.this,1);
            }
            //new Login().getViolationtrainingPayMentApp(userId,orgId, plateNo,sn,this, 1);


        }else if(event.getType()==MessageEvent.TYPE_10)
        {
            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(IllegalLearningPaymentActivity.this);
            builder1.setMessage("你充值失败");
            builder1.setTitle("提示:");
            builder1.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();;
                }
            });

            builder1.create().show();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);//反注册EventBus
        SharedPreferences sp = getSharedPreferences("IllegalLearningPaymentActivity", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.clear();
        edit.commit();
    }
    @Override
    public void initData() {
        img_payback = (ImageView) findViewById(R.id.img_payback);
        tv_pay3 = (TextView)findViewById(R.id.tv_pay3);
        rg = (LiumRadioGroup) findViewById(R.id.rg);
        radioButton_pay1 = (RadioButton) findViewById(R.id.radioButton_pay1);
        img_yu = (ImageView) findViewById(R.id.img_pay);
        tv_pay2 = (TextView) findViewById(R.id.tv_pay2);

        //注册EventBus
        EventBus.getDefault().register(this);
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#1F80C4"));
        Bundle bundle = getIntent().getExtras();
        String orgId = bundle.getString("orgId");
        String plateNo = bundle.getString("plateNo");
        jumpType=bundle.getString("jumpType");
        int sn = bundle.getInt("sn");
        float vtPirce = bundle.getFloat("vtPirce");
        float balance = bundle.getFloat("balance");
        SharedPreferences sp = getSharedPreferences("IllegalLearningPaymentActivity", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("orgId",orgId);
        edit.putString("plateNo",plateNo);
        edit.putInt("sn",sn);
        edit.commit();
        String twoDecimal = getTwoDecimal(vtPirce);
        tv_price.setText(twoDecimal+"元");
        String twoDecimalbalance = getTwoDecimal(balance);

        tv_balance.setText(twoDecimalbalance+"元");

        if(balance<vtPirce)
        {
            float difference=vtPirce-balance;
            String twoDecimal1 = getTwoDecimal(difference);
            float differencefloat = Float.parseFloat(twoDecimal1);
            tv_money.setText("需付金额："+differencefloat+"元");
            edit.putFloat("difference",differencefloat);
            edit.commit();
            img_yu.setImageResource(R.mipmap.wechatpay);
            tv_pay2.setText("微信支付");
            tv_pay3.setText("充值余额并购买");
        }else{
            tv_money.setText("本次购买金额充足");
            img_yu.setImageResource(R.mipmap.balancepayment);
            tv_pay2.setText("余额支付");
            tv_pay3.setText("余额购买");
        }

    }
    /**
     * 将数据保留两位小数
     */
    private String getTwoDecimal(double num) {
        DecimalFormat dFormat = new DecimalFormat("#0.00");
        String yearString = dFormat.format(num);
        return yearString;
    }
    //获取手机的唯一标识
    @SuppressLint("MissingPermission")
    public String getPhoneSign(){
        StringBuilder deviceId = new StringBuilder();
        // 渠道标志
        deviceId.append("a");
        try {
            // IMEI（imei）
            TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            String imei = tm.getDeviceId();
            if(!TextUtils.isEmpty(imei)){
                deviceId.append("imei");
                deviceId.append(imei);
                return deviceId.toString();
            }
            //序列号（sn）
            String sn = tm.getSimSerialNumber();
            if(!TextUtils.isEmpty(sn)){
                deviceId.append("sn");
                deviceId.append(sn);
                return deviceId.toString();
            }
            //如果上面都没有， 则生成一个id：随机码
            String uuid = getUUID();
            if(!TextUtils.isEmpty(uuid)){
                deviceId.append("id");
                deviceId.append(uuid);
                return deviceId.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            deviceId.append("id").append(getUUID());
        }
        return deviceId.toString();
    }
    /**
     * 得到全局唯一UUID
     */
    private String uuid;
    public String getUUID(){
        SharedPreferences mShare = getSharedPreferences("uuid",MODE_PRIVATE);
        if(mShare != null){
            uuid = mShare.getString("uuid", "");
        }
        if(TextUtils.isEmpty(uuid)){
            uuid = UUID.randomUUID().toString();
            mShare.edit().putString("uuid",uuid).commit();
        }
        return uuid;
    }
    @Override
    public void requestData() {

    }
    @Override
    public void onSuccess(String result, Call call, Response response, int what) {

        if(what==1)
        {
            dismissLoadingDialog();
            IllegalLearningPaymentBean illegalLearningPaymentBean = JSON.parseObject(result, IllegalLearningPaymentBean.class);
            final    Integer uvtSn = illegalLearningPaymentBean.getData();
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            View view1 = View.inflate(IllegalLearningPaymentActivity.this, R.layout.diolog_learn_layout, null);
            TextView tv_message = (TextView) view1.findViewById(R.id.message);//输入内容
            tv_message.setText("违章培训购买成功");
            TextView btn_sure = (TextView) view1.findViewById(R.id.positiveButton);
            TextView btn_cancel = (TextView) view1.findViewById(R.id.negativeButton);
            btn_sure.setText("我知道");
            btn_cancel.setVisibility(View.GONE);
            final AlertDialog dialog = builder.create();
            dialog.show();
            dialog.getWindow().setContentView(view1);
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            dialog.setCancelable(false);
            btn_sure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismiss();
                    Bundle bundle = new Bundle();
                    bundle.putInt("uvtSn", uvtSn);
                    bundle.putString("jumpType", "homeFgt");
                    startActivity(SubIllegalLearningActivity.class, bundle);
                    finish();
                    //设置你的操作事项
                }
            });
        }else if(what==2)
        {
            PayMentBean payMentBean = JSON.parseObject(result, PayMentBean.class);
            String msg = payMentBean.getMsg();//支付订单系列号
            SharedPreferences sp1 = getSharedPreferences("msg", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit1 = sp1.edit();
            edit1.putString("msg",msg);
            edit1.putInt("paytag",7);
            edit1.commit();
            PayMentBean.DataBean paydata = payMentBean.getData();//微信服务器返回的结果
            if(paydata!= null)
            {
                api.registerApp(Constants.APP_ID);
                PayReq req = new PayReq();
                req.appId = Constants.APP_ID;
                req.packageValue = "Sign=WXPay";
                req.partnerId = paydata.getPartnerid();
                req.prepayId = paydata.getPrepayid();
                req.nonceStr = paydata.getNoncestr();
                req.timeStamp = paydata.getTimestamp();
                req.sign = paydata.getSign();
                api.sendReq(req);

            }

            tv_pay3.setEnabled(true);
        }
        super.onSuccess(result, call, response, what);
    }

    @Override
    public void onError(String result, Call call, Response response, int what) {
        if(what==1)
        {
            dismissLoadingDialog();
            tv_pay3.setEnabled(true);
            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
            //     int code = checkBean.getCode();
            String msg = checkBean.getMsg();
            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
            builder1.setMessage(msg);
            builder1.setTitle("提示:");
            builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();;
                    //设置你的操作事项
                }
            });
            builder1.create().show();
        }else if(what==2)
        {
            tv_pay3.setEnabled(true);
            CheckBean checkBean = JSON.parseObject(result, CheckBean.class);
            //     int code = checkBean.getCode();
            String msg = checkBean.getMsg();
            TiShiDialog.Builder builder1 = new TiShiDialog.Builder(this);
            builder1.setMessage(msg);
            builder1.setTitle("提示:");
            builder1.setPositiveButton("我知道", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();;
                    //设置你的操作事项
                }
            });
            builder1.create().show();
        }
        super.onError(result, call, response, what);
    }
}
